package com.leoman.plz_p.utils.authority;

import android.content.Context;

import com.leoman.plz_p.module.bean.User;
import com.leoman.plz_p.views.enterprise.LoginActivity;

import cn.com.corelib.utils.AppManager;
import cn.com.corelib.utils.PreferencesHelper;


/**
 * 权限控制
 * Created by Ryan on 2016/1/6.
 */
public class AuthorityContext {
    private static AuthorityContext context;
    private Authority authority;

    private AuthorityContext() {
        User user = PreferencesHelper.getData(User.class);
        if (user == null || user.getId()<=0) loggedOut();
        else loggedIn();
    }

    public static AuthorityContext getContext() {
        if (context == null)  context = new AuthorityContext();
        return context;
    }

    public void setAuthority(Authority authority) {
        this.authority = authority;
    }

    public void loggedIn() {
        setAuthority(new LoggedIn());
    }

    public void loggedOut() {
        setAuthority(new LoggedOut());
    }

    public boolean isLoggedIn() {
        return authority instanceof LoggedIn;
    }

    /**
     * 检查是否有权限, 如未登录则进入登录页面
     * @return 是否有权限
     */
    public boolean checkAuthority(Context context) {
        if (!isLoggedIn()) {
            try {
                Thread.sleep(200);
                if (!AppManager.getAppManager().currentActivity().getClass().getName().contains("LoginActivity"))
                    context.startActivity(LoginActivity.getLaunchIntent(context));
                return false;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        return true;
    }
}
